package main

import (
	"bytes"
	"crypto/cipher"
	"crypto/des"
	"encoding/base64"
	"fmt"
)

type TripleDES struct {
	key string
	iv  string
}

func (t *TripleDES) Encrypt(plain string) (string, error) {
	key := []byte(t.key)
	iv := []byte(t.iv)

	block, err := des.NewTripleDESCipher(key)
	if err != nil {
		return "", err
	}
	// 创建 CBC 分组模式
	mode := cipher.NewCBCEncrypter(block, iv)
	data := PKCS5Padding([]byte(plain), block.BlockSize())
	// 加密数据
	encryptedData := make([]byte, len(data))
	mode.CryptBlocks(encryptedData, data)

	return base64.StdEncoding.EncodeToString(encryptedData), err
}

func (t *TripleDES) Decrypt(secret string) (string, error) {
	key := []byte(t.key)
	iv := []byte(t.iv)

	crypted, err := base64.StdEncoding.DecodeString(secret)
	if err != nil {
		return "", err
	}
	block, err := des.NewTripleDESCipher(key)
	if err != nil {
		return "", err
	}
	// 创建 CBC 分组模式
	mode := cipher.NewCBCDecrypter(block, iv)

	// 解密数据
	decryptedData := make([]byte, len(crypted))
	mode.CryptBlocks(decryptedData, crypted)
	origData := PKCS5UnPadding(decryptedData)
	return string(origData), nil
}

func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

func PKCS5UnPadding(origData []byte) []byte {
	length := len(origData)
	// 去掉最后一个字节 unpadding 次
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}
func main() {
	//accesskey := []byte("50b13132bb394901f151bc12")            // 16字节的密钥
	//key := []byte("9cb1b781871e4d24ad686a3d028ea9e9")
	key := []byte("8bb1b781871d4d24ad787a2d")

	iv := []byte("12345678") // 8字节的向量（IV）

	plaintext := `{"totalNumber":1}`

	t := TripleDES{
		key: string(key[:24]),
		iv:  string(iv),
	}
	re, err := t.Encrypt(plaintext)
	if err != nil {
		fmt.Println(err, "加密失败", err.Error())
		return
	}
	fmt.Println("加密后的数据：", re)

	// 解密
	decrypt, err := t.Decrypt(re)
	if err != nil {
		fmt.Println(err, "解密失败", err.Error())
		return
	}
	fmt.Println("解密后的数据：", decrypt)

	pdata := "8bjPWUboekDr1bgqj/X5ZLVfcoQ1EJ2nKmvwNuFKT1VuobxtSAeWG+2+M9e0mKo/HhICrmM3+KZ7BpqumHOR+NKanzVDZZg+"
	decrypt2, err := t.Decrypt(pdata)
	if err != nil {
		fmt.Println(err, "解密失败2", err.Error())
		return
	}
	fmt.Println(decrypt2)
}
